package org.ajax.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.ajax.entity.Student;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 模拟DAO - 查询学生列表 - 转换为JSON字符串 - 响应到客户端页面
 * @author CSY
 * @date 2024-11-18
 */
@WebServlet("/list.do")
public class ListDataServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求编码，没有请求就可以不用设置 req.getParameter("") - 获得请求数据
        req.setCharacterEncoding("UTF-8");
        //设置响应编码
        resp.setCharacterEncoding("UTF-8");
//        resp.setContentType("text/html;charset=UTF-8");

        List<Student> list = new ArrayList<>();
        Student s1 = new Student("张三",18,99,new Date());
        Student s2 = new Student("李四",20,88,new Date());
        Student s3 = new Student("王五",22,77,new Date());
        
        list.add(s1);
        list.add(s2);
        list.add(s3);

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();

        String json = gson.toJson(list);

        PrintWriter out = resp.getWriter();

        out.println(json);

        out.flush();
        out.close();
    }
}
